<template>
<!--  <div class="assess-top">-->
<!--    <el-dialog v-if="uploadServerSingleVisible" title="上传文件" :visible.sync="uploadServerSingleVisible">-->
    <el-dialog title="上传文件" :visible.sync="uploadServerSingleVisible">
<!--      <div class="el-dialog-div-upload">-->
        <el-form ref="OCRUpload" :model="batchUpload" label-width="100px" class="OCRUploadDialogue" size="small">
          <el-row :gutter="10" class="el-row">
            <el-col :span="12" :offset="4" >
              <div class="grid-content bg-purple">
                <el-form-item label="导入文件:" style="padding-top: 16px">
                  <el-upload
                    ref="batchUpload"
                    :limit="1"
                    :file-list="fileList"
                    action="#"
                    :on-change="handleChange"
                    :headers="batchUpload.headers"
                    :disabled="batchUpload.isUploading"
                    :on-progress="handleFileUploadProgress"
                    :on-success="handleFileSuccess"
                    :auto-upload="false"
                    accept=".jpg,.png,"
                    drag >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“jpg/png格式文件”，且不超过10M！</div>
                  </el-upload>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
<!--      </div>-->
      <span slot="footer" class="dialog-footer">
            <el-button type="primary" size="mini" @click="submitFileForm()">确定</el-button>
            <el-button size="mini" @click="uploadServerSingleVisible = false">取消</el-button>
        </span>
    </el-dialog>
<!--  </div>-->

</template>

<script>
/* eslint-disable */
import axios from 'axios'
export default {
  /*todo: 文件转base64信息并前后端交互，最终上传到服务器*/
  name: 'uploadServerSingle',
  props: {
    /** 如果需要额外通过此传参来处理业务逻辑，可在父页面传参控制*/
    moduleName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      uploadServerSingleVisible: false,
      // 导入参数
      batchUpload: {
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        // headers: { Authorization: "Bearer " + getToken() },
      },
      fileObj: {},
      fileList: [],
      moduleNameValue: this.moduleName,
    }
  },
  created() {
  },
  methods: {
    // 文件上传前对文件类型、文件大小判断限制
    handleChange(file) {
      if (file.status !== "ready") return;
      this.fileObj = file;
      this.fileList.push(file)
      const {name, size} = file;
      const index = name.lastIndexOf('.');
      // 判断文件名是否有后缀，没后缀文件错误
      if (index === -1) {
        this.$alert('文件错误，请重新上传！', '警告', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        this.fileList = []
        return false;
      }
      const fileType = name.substr(index + 1);
      const acceptFileTypes = ['jpg', 'png'];
      // 判断文件类型
      if (!acceptFileTypes.includes(fileType)) {
        this.$alert('文件类型错误, 仅允许导入“jpg/png格式文件”,请重新上传！', '警告', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        this.fileList = []
        return false;
      }
      // 判断文件大小
      if (size > 10 * 1024 * 1024) {
        this.$alert('文件大小超过10M，请重新上传！', '警告', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        this.fileList = []
        return false;
      }
      return true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.batchUpload.isUploading = true;
    },
    // 文件上传成功(调接口成功后)的处理
    handleFileSuccess(response, file, fileList) {

    },
    // 提交上传文件
    async submitFileForm() {
      console.log("fileList >>>", this.fileList)
      console.log("fileList length >>>", this.fileList.length)
      if(this.fileList.length <= 0) {
        this.$message.warning('请先上传文件！')
        return;
      } else {
        let imgResult = '';
        await this.getBase64(this.fileObj).then(res => {
          imgResult = res
        });
        let name = this.fileObj.name
        let suffix = name.substring(name.lastIndexOf("."))
        let paramFileList = []
        paramFileList.push({
          base64FileInfo: imgResult,
          suffix: suffix,
        })
        console.log('paramFileList >>>' , paramFileList)

        this.$http({
          url: this.$http.adornUrl("/thirdPart/upload/server"),
          method: "post",
          data: this.$http.adornData({
            uploadType: 'product',
            isSingleFile: '1',
            fileList: paramFileList,
            operateType: '0',
            deletePaths: []
          }, false)
        }).then(({ data }) => {
          console.log('data  >>>', data)
          // 成功
          // this.uploadServerSingleVisible = false
        });
      }
    },
    // 提交上传文件
    async submitFileFormWithBase64Info() {
      let imgResult = '';
      await this.getBase64(this.fileObj).then(res => {
        imgResult = res
      });
      // 后续可以使用 Base64转码后的文件信息， 可调试接口使用
      let param = {
        // cardType: this.ocrPageFlag,
        imgBase64Info: imgResult,
      }
    },
    // 上传文件转Base64格式
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file.raw);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          imgResult = reader.result;
          resolve(imgResult);
        };
      });
    },
  },


}


</script>

<style lang="scss" scoped>
/**  .el-dialog-div {
    height: 60vh;
    overflow: auto;
  } */
::v-deep .OCRUpload .el-dialog__body {
  padding: 16px;
}

.el-dialog-div-upload {
  height: 20vh;
}

</style>
